//
//  YHOptionTableViewController.m
//  ScriptKill
//
//  Created by 林宁宁 on 2021/4/27.
//  Copyright © 2021 优智汇. All rights reserved.
//

#import "YHOptionTableViewController.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "YHOptionLayoutConstant.h"
#import "YHOptionTitleTableViewCell.h"
#import "YHOptionTableViewItemCustomStyle.h"
#import "YHDeviceInfo.h"
#import "NSObject+Keyboard.h"
#import "UIView+YH.h"
#import "NSArray+YYAdd.h"

@interface YHOptionTableViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (retain, nonatomic, readwrite) NSMutableArray <YHOptionTableViewItem *> * dataList;

@property (retain, nonatomic, readwrite) UITableView * tableView;

/// 自定义cell的map 不重用
@property (retain, nonatomic) NSMutableDictionary * customCellMap;

@end

@implementation YHOptionTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStylePlain)];
    self.tableView.rowHeight = Adapted(50);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 13)];
    self.tableView.separatorColor = [UIColor yh_separator];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.estimatedRowHeight = 0;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 60+[YHDeviceInfo height_home_indicator], 0);
    [self.view addSubview:self.tableView];
    if (@available(iOS 15.0,*)) {
         self.tableView.sectionHeaderTopPadding = 0;
    }
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self yh_keyboardShowAtAnimationView:self.tableView];
    
    self.dataList = [NSMutableArray new];
    self.customCellMap = [NSMutableDictionary new];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataList.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    YHOptionTableViewItem * item = self.dataList[indexPath.section];
    if(item.layout.cellHeightAuto){
        if(item.layout.cellHeightFix){
            return item.layout.cellHeightFix;
        }
        CGFloat height = 0;
        if(item.cellHeightCalculationBlock){
            height = item.cellHeightCalculationBlock(indexPath,item);
        }else{
            height = [tableView fd_heightForCellWithIdentifier:item.cellIdentify configuration:^(YHBaseTableViewCell *  cell) {
                if(item.cellShowBlock){
                    item.cellShowBlock(cell, item);
                }
            }];
        }
        return MAX(item.layout.cellHeight, height);
    }
    return item.layout.cellHeight;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WS(weakSelf)
    YHOptionTableViewItem * item = self.dataList[indexPath.section];
    
    YHBaseTableViewCell * cell;
    if([item isKindOfClass:YHOptionTableViewItemCustomStyle.class]){
        cell = self.customCellMap[item.cellIdentify];
        if(!cell){
            cell = [item.cellClass new];
            self.customCellMap[item.cellIdentify] = cell;
        }
    }else{
        cell = [tableView dequeueReusableCellWithIdentifier:item.cellIdentify forIndexPath:indexPath];
    }
    
    cell.indexPath = indexPath;
    
    cell.backgroundColor = [UIColor clearColor];
    cell.contentView.backgroundColor = [UIColor clearColor];
    cell.cellContent.backgroundColor = item.layout.cellBgColor;
    
    cell.showAccessoryArrowView = item.layout.showAccessoryArrowView;
    cell.showBottomLine = item.layout.showBottomLine;
    
    if([cell isKindOfClass:[YHOptionTitleTableViewCell class]]){
        YHOptionTitleTableViewCell * opCell = (YHOptionTitleTableViewCell *)cell;
        
        opCell.contentHorizontalSpac = item.layout.spaceHorizontalMargin;
        
        // 左侧视图信息
        [opCell updateLeftContentByItem:item];

        // 右侧视图信息
        [opCell updateRightContentByItem:item];
        
        [opCell setRightViewEvent:^(NSIndexPath * _Nonnull passIndexPath, YHOptionCellRightShowType rightShowType, YHOptionTitleTableViewCell * _Nonnull passCell, NSString * _Nonnull passValue) {
            YHOptionTableViewItem * passItem = weakSelf.dataList[passIndexPath.section];
            if(rightShowType & YHOptionCellRightShowType_Clean){
                [passCell endEditing:YES];
                [passItem.rightContent clean];
                passItem.content = @"";
                passItem.pickerContents = @"";
                [weakSelf reloadOptionItem:passItem];
                if(passItem.cellCleanBlock){
                    passItem.cellCleanBlock(passIndexPath, passItem);
                }
            }
            else{
                if(rightShowType & YHOptionCellRightShowType_Switch){
                    passItem.rightContent.isOn = [passValue boolValue];
                    if(passItem.cellRightClickBlock){
                        passItem.cellRightClickBlock(passIndexPath, passItem,passItem.layout.rightShowType,passItem.rightContent);
                    }
                }else{
                    
                }
            }
        }];
    }
    
    if(item.cellShowBlock){
        item.cellShowBlock(cell, item);
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.view endEditing:YES];
    
    YHOptionTableViewItem * item = self.dataList[indexPath.section];
    if(item.cellClickBlock){
        item.cellClickBlock(indexPath, item);
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    YHOptionTableViewItem * item = self.dataList[section];
    return MAX(0.001, item.layout.spaceTop);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    YHOptionTableViewItem * item = self.dataList[section];
    return MAX(0.001, item.layout.spaceBottom);
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    YHOptionTableViewItem * item = self.dataList[section];
    UIView * headerView = [UIView new];
    headerView.backgroundColor = item.layout.spaceColorTop;
    return headerView;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    YHOptionTableViewItem * item = self.dataList[section];
    UIView * footerView = [UIView new];
    footerView.backgroundColor = item.layout.spaceColorBottom;
    return footerView;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(YHBaseTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    YHOptionTableViewItem * item = self.dataList[indexPath.section];

    if(item.layout.cornerType){
        [cell.cellContent corner:item.layout.cornerRadius pos:item.layout.cornerType];
    }else{
        [cell.cellContent cornerNone];
    }
}


#pragma mark -

- (void)addOptionItem:(YHOptionTableViewItem *)item{
    
    [self.tableView registerClass:item.cellClass forCellReuseIdentifier:item.cellIdentify];
    [self.dataList addObject:item];
    
    WS(weakSelf)
    
    [self yh_kvoForKeyPaths:@[@"rightContent.imageURL",@"rightContent.isOn",@"rightContent.title",@"rightContent.attibutedTitle"] observe:item block:^(id  _Nonnull obj, id  _Nullable oldVal, id  _Nullable newVal) {
        if([obj isKindOfClass:YHOptionTableViewItem.class]){
            YHOptionTableViewItem * item = (YHOptionTableViewItem *)obj;
            if(!item.changeShouldReload){
                return;
            }
        }
        if([weakSelf.dataList containsObject:obj]){
            NSInteger section = [weakSelf.dataList indexOfObject:obj];
            NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:section];
            YHOptionTitleTableViewCell * opCell = (YHOptionTitleTableViewCell *)[weakSelf.tableView cellForRowAtIndexPath:indexPath];
            if([opCell isKindOfClass:YHOptionTitleTableViewCell.class]){
                [opCell updateRightContentByItem:obj];
            }
        }
    }];
    
    [self yh_kvoForKeyPaths:@[@"leftContent.imageURL",@"leftContent.isOn",@"leftContent.title",@"leftContent.attibutedTitle"] observe:item block:^(id  _Nonnull obj, id  _Nullable oldVal, id  _Nullable newVal) {
        if([obj isKindOfClass:YHOptionTableViewItem.class]){
            YHOptionTableViewItem * item = (YHOptionTableViewItem *)obj;
            if(!item.changeShouldReload){
                return;
            }
        }
        if([weakSelf.dataList containsObject:obj]){
            NSInteger section = [weakSelf.dataList indexOfObject:obj];
            NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:section];
            YHOptionTitleTableViewCell * opCell = (YHOptionTitleTableViewCell *)[weakSelf.tableView cellForRowAtIndexPath:indexPath];
            if([opCell isKindOfClass:YHOptionTitleTableViewCell.class]){
                [opCell updateLeftContentByItem:obj];
            }else{
                [weakSelf reloadOptionItem:obj];
            }
        }
    }];
    
    [self yh_kvoForKeyPaths:@[
        @"content",
        @"pickerContents"
    ] observe:item block:^(YHOptionTableViewItem *  _Nonnull obj, id  _Nullable oldVal, id  _Nullable newVal) {
        
        if([obj isKindOfClass:YHOptionTableViewItemInputTextFiled.class]){
            YHOptionTableViewItemInputTextFiled * item = (YHOptionTableViewItemInputTextFiled *)obj;
            if(item.editAble){
                return;
            }
        }
        else if([obj isKindOfClass:YHOptionTableViewItemInputTextView.class]){
            YHOptionTableViewItemInputTextView * item = (YHOptionTableViewItemInputTextView *)obj;
            if(item.editAble){
                return;
            }
        }
        else if([obj isKindOfClass:YHOptionTableViewItem.class]){
            YHOptionTableViewItem * item = (YHOptionTableViewItem *)obj;
            if(!item.changeShouldReload){
                return;
            }
        }

        [weakSelf reloadOptionItem:obj];
    }];
}
- (void)addOptionItems:(NSArray <YHOptionTableViewItem *>*)items{
    for(YHOptionTableViewItem * item in items){
        [self addOptionItem:item];
    }
}
- (void)insertOptionItems:(NSArray <YHOptionTableViewItem *>*)items below:(YHOptionTableViewItem *)below{
    if(![self.dataList containsObject:below]){
        return;
    }
    NSInteger index = [self.dataList indexOfObject:below];
    [self.dataList insertObjects:items atIndex:index+1];
}
- (void)removeOptionItem:(YHOptionTableViewItem *)item{
    [self.dataList removeObject:item];
}
- (void)removeOptionItems:(NSArray <YHOptionTableViewItem *>*)items{
    [self.dataList removeObjectsInArray:items];
}
- (void)reloadOptionItem:(YHOptionTableViewItem *)item{
    if([self.dataList containsObject:item]){
        NSInteger section = [self.dataList indexOfObject:item];
        [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:section]] withRowAnimation:(UITableViewRowAnimationNone)];
    }
}
- (void)reloadOptionItems:(NSArray <YHOptionTableViewItem *>*)items{
    NSMutableArray * indexPaths = [NSMutableArray new];
    for(YHOptionTableViewItem * item in items){
        if([self.dataList containsObject:item]){
            NSInteger section = [self.dataList indexOfObject:item];
            [indexPaths addObject:[NSIndexPath indexPathForRow:0 inSection:section]];
        }
    }
    if(indexPaths.count > 0){
        [self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:(UITableViewRowAnimationNone)];
    }
}

- (YHOptionTableViewItem *)filterOptionByID:(NSString *)ID{
    for (YHOptionTableViewItem * item  in self.dataList) {
        if([item.optionID isEqualToString:ID]){
            return item;
        }
    }
    return nil;
}
- (YHOptionTableViewItem *)filterOptionByCellType:(NSInteger)cellType{
    for (YHOptionTableViewItem * item  in self.dataList) {
        if(item.cellType == cellType){
            return item;
        }
    }
    return nil;
}
- (YHOptionTableViewItem *)filterOptionByIndex:(NSInteger)index{
    if(index < self.dataList.count){
        return self.dataList[index];
    }
    return nil;
}

- (NSArray <YHOptionTableViewItem *>*)allOptionList{
    return self.dataList;
}

- (void)cleanAllOptions{
    [self.dataList removeAllObjects];
}

- (void)reloadContentView{
    [self.tableView reloadData];
}

/// 判断所有的条件是否 满足
- (BOOL)isAviableOptionItems{
    for(YHOptionTableViewItem * item in self.dataList){
        if(item.isRequire){
            if(![item isAviableToHint]){
                return NO;
            }
        }
    }
    return YES;
}

@end



